package com.crack.nga2.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;

import com.crack.nga2.utils.GlobalConst;

/**
 * 一个监视网络的service，网络发生变化时将会改变全局变量的值
 */
public class InternetStateService extends Service {

    private BroadcastReceiver receiver;
    private ConnectivityManager connectivityManager;
    private NetworkInfo info;

    public InternetStateService() {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    info = connectivityManager.getActiveNetworkInfo();
                    if (info != null && info.isAvailable()) {
                        NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                        GlobalConst.WIFI_AVAILABLE = wifi != null && wifi.isAvailable();
                        NetworkInfo mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                        GlobalConst.MOBILE_AVAILABLE = mobile != null && mobile.isAvailable();
                    } else {
                        GlobalConst.NETWORK_AVAILABLE = false;
                        GloabalConst.MOBILE_AVAILABLE = false;
                        GloabalConst.WIFI_AVAILABLE = false;
                    }
                }
            }
        };
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver,filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
